package com.wheatek.navigation

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.findNavController

class MainActivity : AppCompatActivity() {

    private val navController: NavController?
        get() {
            return try {
                findNavController(R.id.my_nav_host_fragment)
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navController?.addOnDestinationChangedListener { controller, destination, arguments ->
            // actionbar显示对应fragment的title
            supportActionBar?.title = destination.label
            val graph = controller.graph
            // 不是首页则显示返回按钮
            supportActionBar?.setDisplayHomeAsUpEnabled(
                destination != graph.findNode(graph.startDestination)
            )
        }
    }


    // 控制返回按钮
    override fun onSupportNavigateUp() = navController?.navigateUp() ?: false
}